﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using ModuleBase;
using Prism.Ioc;

namespace HostComputerPlatform.Services
{
    public class CustomModuleManager
    {
        private readonly string _modulePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Modules");
        private readonly IContainerProvider _containerProvider;
        private readonly List<Type> _loadedModuleTypes = new List<Type>();

        public CustomModuleManager(IContainerProvider containerProvider)
        {
            _containerProvider = containerProvider;
        }

        public IEnumerable<Type> LoadModules()
        {
            if (!Directory.Exists(_modulePath))
            {
                Directory.CreateDirectory(_modulePath);
                return _loadedModuleTypes;
            }

            foreach (var dllPath in Directory.GetFiles(_modulePath, "*.dll"))
            {
                try
                {
                    var assembly = Assembly.LoadFrom(dllPath);

                    var types = assembly.GetTypes()
                        .Where(t => typeof(IModuleBase).IsAssignableFrom(t) && !t.IsAbstract);

                    foreach (var type in types)
                    {
                        if (!_loadedModuleTypes.Contains(type))
                        {
                            _loadedModuleTypes.Add(type);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"Failed to load module from {dllPath}: {ex.Message}");
                }
            }

            return _loadedModuleTypes;
        }

        public IModuleBase CreateModuleInstance(Type moduleType)
        {
            return _containerProvider.Resolve(moduleType) as IModuleBase;
        }

        public Type GetModuleType(string moduleTypeName)
        {
            return _loadedModuleTypes.FirstOrDefault(t => t.FullName == moduleTypeName);
        }
    }
}